<template>
  <div>
    <el-radio-group v-model="coordType" style="margin: 10px 0;">
      <el-radio value="wgs">wgs84</el-radio>
      <el-radio value="gcj">gcj02</el-radio>
      <el-radio value="cgcs">cgcs2000</el-radio>
      <el-radio value="cgcs">wgs84高斯投影</el-radio>
      <el-radio value="cgcs">ecef</el-radio>
    </el-radio-group>
    <div class="inputBox">
      <span>原坐标：</span>
      <el-input style="width: 300px;margin: 0 10px;" v-model="lnglat" />
      <el-select v-if="coordType == 'cgcs'" placeholder="请选择三度分带号" v-model="cgcsdh" style="width: 180px">
        <el-option v-for="(item, ind) in cgcsArr" :key="ind" :value="item.val">{{ item.name }}</el-option>
      </el-select>
      <el-button type="primary" @click="startConvert">转换</el-button>
    </div>
    <table class="tab" border="1px">
      <tr>
        <td>WGS84(lng,lat)</td>
        <td width="350">{{ wgsVal }}</td>
      </tr>
      <tr>
        <td>GCJ02(lng,lat)</td>
        <td>{{ gcjVal }}</td>
      </tr>
      <tr>
        <td>CGCS2000(east,north)</td>
        <td>{{ CGCSVal }}</td>
      </tr>
    </table>
    <input type="file" @change="handleUpload" accept=".xlsx, .xls" />
    <button @click="conversionAll">转换并导出</button>
  </div>
</template>
  
<script>
import * as XLSX from 'xlsx';
import { coordConvert } from "./coord"
export default {
  mixins: [coordConvert],
  data() {
    return {
      coordType: "wgs",
      lnglat: "",//输入坐标
      wgsVal: "",//wgs坐标
      gcjVal: "",// 火星坐标
      CGCSVal: "", //2000坐标
      cgcsdh: "75", //三分度带号
      cgcsArr: [], // 3度分带号
      parsedData: [], //导入及导出数据
      allTitle: [], //导出表头
    };
  },
  mounted() {
    let dh = []
    Array.from({ length: 21 }, (_, ind) => {
      const zoneNumber = 25 + ind;
      const longitude = 75 + ind * 3;

      // 创建对象并推送到数组中
      const obj = {
        name: `3度分带号${zoneNumber} - ${longitude}E`,
        val: longitude + ''
      };
      dh.push(obj)
    })
    this.cgcsArr = dh
  },
  methods: {
    startConvert() {
      if (!this.lnglat) this.$message.warn('请输入坐标')
      // 使用正则表达式匹配中文逗号或英文逗号，并拆分字符串
      let lnglat = this.lnglat.split(/[,，]/);
      lnglat[0] = Number(lnglat[0])
      lnglat[1] = Number(lnglat[1])
      switch (this.coordType) {
        case 'wgs':
          this.wgsVal = lnglat.join(',')
          this.gcjVal = this.wgs84ToGcj02(lnglat[0], lnglat[1]).join(',')
          this.CGCSVal = this.wgs84ToCgcs2000(lnglat[0], lnglat[1]).join(',')
          let PseudoMercator=this.wgs84ToPseudoMercator(lnglat[0], lnglat[1])
          console.log("PseudoMercator",PseudoMercator);
          break;
        case 'gcj':
          this.gcjVal = this.lnglat
          let wgsTemp = this.Gcj02ToWgs84(lnglat[0], lnglat[1])
          this.wgsVal = wgsTemp.join(',')
          this.CGCSVal = this.wgs84ToCgcs2000(wgsTemp[0], wgsTemp[1]).join(',')
          break;
        case 'cgcs':
          let ind = this.cgcsArr.findIndex(s => s.val == this.cgcsdh)
          this.CGCSVal = this.lnglat + ',' + (ind + 25)
          let wgs84Temp = this.Cgcs2000ToWgs84(lnglat[0], lnglat[1], this.cgcsdh)
          this.wgsVal = wgs84Temp.join(',')
          this.gcjVal = this.wgs84ToGcj02(wgs84Temp[0], wgs84Temp[1]).join(',')
          break;

        default:
          break;
      }
    },
    handleUpload() {
      let _this = this
      const file = event.target.files[0];

      if (file) {
        const reader = new FileReader();

        reader.onload = (e) => {
          const data = e.target.result;
          const workbook = XLSX.read(data, { type: 'binary' });

          // Assuming the data is in the first sheet
          const sheetName = workbook.SheetNames[0];
          const sheet = workbook.Sheets[sheetName];

          // Convert sheet to array of objects
          const dataArray = XLSX.utils.sheet_to_json(sheet, { header: 1 });
          // console.log("dataArray",dataArray);
          let title = dataArray[0]
          // Skip the header row and convert the rest to the desired format
          _this.parsedData = dataArray.slice(1).map(row => {
            return {
              // [`${title[0]}`]: row[0].toString(),
              // [`${title[1]}`]: row[1].toString(),
              "lng/X":Number(row[0]),
              "lat/Y": Number(row[1]),
            };
          });
          // console.log("_this.parsedData", _this.parsedData);
        };

        reader.readAsBinaryString(file);
      }
    },
    // 批量转换
    conversionAll() {
      this.allTitle = ["lng/X", "lat/Y", "wgs84lng", "wgs84lat", "gcj02lng", "gcj02lat", "cgcs2000X", "cgcs2000Y"]
      switch (this.coordType) {
        case 'wgs':
          this.parsedData.forEach(sour => {
            sour.wgs84lng = sour['lng/X'].toString()
            sour.wgs84lat = sour['lat/Y'].toString()
            let gcjVal = this.wgs84ToGcj02(sour['lng/X'], sour['lat/Y'])
            sour.gcj02lng = gcjVal[0].toString()
            sour.gcj02lat = gcjVal[1].toString()
            let CGCSVal = this.wgs84ToCgcs2000(sour['lng/X'], sour['lat/Y'])
            sour.cgcs2000X = CGCSVal[0].toString()
            sour.cgcs2000Y = CGCSVal[1].toString()
          })
          break;
        case 'gcj':
          this.parsedData.forEach(sour => {
            sour.gcj02lng = sour['lng/X'].toString()
            sour.gcj02lat = sour['lat/Y'].toString()
            let wgsTemp = this.Gcj02ToWgs84(sour['lng/X'], sour['lat/Y'])
            sour.wgs84lng = wgsTemp[0].toString()
            sour.wgs84lat = wgsTemp[1].toString()
            let CGCSVal = this.wgs84ToCgcs2000(wgsTemp[0], wgsTemp[1])
            sour.cgcs2000X = CGCSVal[0].toString()
            sour.cgcs2000Y = CGCSVal[1].toString()
          })
          break;
        case 'cgcs':
          this.parsedData.forEach(sour => {
            sour.cgcs2000X = sour['lng/X'].toString()
            sour.cgcs2000Y = sour['lat/Y'].toString()
            let wgs84Temp = this.Cgcs2000ToWgs84(sour['lng/X'], sour['lat/Y'], this.cgcsdh)
            sour.wgs84lng = wgs84Temp[0].toString()
            sour.wgs84lat = wgs84Temp[1].toString()
            let gcjVal = this.wgs84ToGcj02(wgs84Temp[0], wgs84Temp[1])
            sour.gcj02lng = gcjVal[0].toString()
            sour.gcj02lat = gcjVal[1].toString()
          })
          break;

        default:
          break;
      }
      this.modifyAndExport()
    },
    // 导出
    modifyAndExport() {
      // Create a new worksheet
      const ws = XLSX.utils.json_to_sheet(this.parsedData);

      // Add header row
      // XLSX.utils.sheet_add_aoa(ws, [this.allTitle], { origin: -1 });

      // Create a new workbook and add the worksheet
      const wb = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');

      // Export the workbook to an Excel file
      XLSX.writeFile(wb, '转换后坐标数据.xlsx');
    }
  },
};
</script>
<style scoped>
.inputBox {
  display: flex;
  align-items: center;
}

.tab {
  width: 100%;
  max-width: 500px;
  margin-top: 10px;
}

.tab tr {
  line-height: 40px;
}
</style>
  